﻿using Newtonsoft.Json;
using System.Text.RegularExpressions;

namespace Region.Spider
{
    public static class Tools
    {
        public const int MaxCodeLength = 12;

        public static JsonSerializerSettings JsonSerializerSettings =>
            new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            };

        public static string FormatCode(string code, int len = 0)
        {
            var nCode = code.TrimEnd('0');
            var xLen = nCode.Length;
            if (nCode.Length % 2 != 0)
                xLen += 1;
            if (code.Length > len)
                code = code.Substring(0, xLen);
            return code;
            //if (code.Length > MaxCodeLength)
            //    code = code.Substring(0, MaxCodeLength);
            //return code.PadRight(MaxCodeLength, '0');
        }

        public static string FormatName(string name)
        {
            return name.Replace("\n", "");
        }

        public static string GetCodeFromHref(string href, int len)
        {
            // 正则表达式模式来匹配 href 属性中的数字部分
            string pattern = @"[0-9]+";

            // 执行正则表达式匹配
            Match match = Regex.Match(href, pattern);

            if (match.Success)
            {
                return FormatCode(match.Groups[0].Value, len);
            }
            else
            {
                throw new Exception($"FormatIdFromHref error:{href}");
            }
        }


        //public static async Task CreateAoshangFileAsync(List<AreaItem> items, string filePath)
        //{
        //    var json = JsonConvert.SerializeObject(items,JsonSerializerSettings);
        //    await File.WriteAllTextAsync(filePath, json);
        //}

        public static async Task GenerateJsonFileAsync(object obj, string filePath)
        {
            var json = JsonConvert.SerializeObject(obj, JsonSerializerSettings);
            await File.WriteAllTextAsync(filePath, json);
        }

        public static async Task<T> ReadToJsonAsync<T>(string filePath) 
        {
            string text = await File.ReadAllTextAsync(filePath);
            return JsonConvert.DeserializeObject<T>(text);
        }
    }
}
